package com.example.administrator.ardemo.panorama.image;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Button;

import com.example.administrator.ardemo.R;
import com.example.administrator.ardemo.utils.image.ImageEntity;
import com.example.administrator.ardemo.utils.image.OnCallback;
import com.example.administrator.ardemo.utils.image.SystemUtil;
import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;

import java.io.InputStream;

/**
 * 360度全景图片
 */
public class ImageActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "VrPanorama";

    private VrPanoramaView panoWidgetView;
    private String fileUri = "kong.jpg";//assets文件夹下的文件名
    private VrPanoramaView.Options panoOptions = new VrPanoramaView.Options();
    private ImageLoaderTask backgroundImageLoaderTask;

    private Button btn;
    private SystemUtil systemUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);

        panoWidgetView = findViewById(R.id.pano_view);//初始化VrPanoramaView
        panoWidgetView.setEventListener(new ActivityEventListener());//为VrPanoramaView添加监听
        //panoWidgetView.setFullscreenButtonEnabled (false); //隐藏全屏模式按钮
        //panoWidgetView.setInfoButtonEnabled(false); //隐藏信息按钮
        //panoWidgetView.setStereoModeButtonEnabled(false);//隐藏VR模式按钮
        //panoWidgetView.setDisplayMode(2);  //进入全屏模式

        //TYPE_MONO，图像被预期以覆盖沿着其水平轴360度，而垂直范围是根据图像的宽高比来计算。例如，如果一个1000x250像素的图像，给出所述全景将覆盖360x90度与垂直范围是-45至+45度。
        //TYPE_STEREO_OVER_UNDER，包含两个大小相等的投影 全景图垂直叠加。顶部图像被显示给左眼、底部图像被显示给右眼。
        panoOptions.inputType = VrPanoramaView.Options.TYPE_MONO;

        if (backgroundImageLoaderTask != null)
            backgroundImageLoaderTask.cancel(true);
        new ImageLoaderTask2().execute(Pair.create(fileUri, panoOptions));

        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this);
        systemUtil = new SystemUtil();
    }

    @Override
    public void onClick(View v) {
        systemUtil.openImages(this);
    }

    /**
     * 异步任务加载图片
     */
    class ImageLoaderTask extends AsyncTask<Pair<Bitmap, VrPanoramaView.Options>, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Pair<Bitmap, VrPanoramaView.Options>... fileInformation) {
            InputStream istr = null;
            try {
                Bitmap bitmap = fileInformation[0].first;
                panoWidgetView.loadImageFromBitmap(bitmap, fileInformation[0].second);
                istr.close();
            } catch (Exception e) {
                Log.e(TAG, e.getLocalizedMessage());
                return false;
            }
            return true;
        }
    }

    /**
     * 异步任务加载图片
     */
    class ImageLoaderTask2 extends AsyncTask<Pair<String, VrPanoramaView.Options>, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Pair<String, VrPanoramaView.Options>... fileInformation) {
            InputStream istr = null;
            try {
                istr = getAssets().open(fileInformation[0].first);
                Bitmap bitmap = BitmapFactory.decodeStream(istr);
                panoWidgetView.loadImageFromBitmap(bitmap, fileInformation[0].second);
                istr.close();
            } catch (Exception e) {
                Log.e(TAG, e.getLocalizedMessage());
                return false;
            }
            return true;
        }
    }

    private class ActivityEventListener extends VrPanoramaEventListener {

        @Override
        public void onLoadSuccess() {//图片加载成功
            Log.e(TAG, "onLoadSuccess");
        }

        @Override
        public void onLoadError(String errorMessage) {//图片加载失败
            Log.e(TAG, "Error loading pano: " + errorMessage);
        }

        @Override
        public void onClick() {//当我们点击了VrPanoramaView 时候触发
            super.onClick();
            Log.e(TAG, "onClick");
        }

        @Override
        public void onDisplayModeChanged(int newDisplayMode) {//改变显示模式时候触发（全屏模式和纸板模式）
            super.onDisplayModeChanged(newDisplayMode);
            Log.e(TAG, "onDisplayModeChanged");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        panoWidgetView.pauseRendering();//暂停3D渲染和跟踪
    }

    @Override
    protected void onResume() {
        super.onResume();
        panoWidgetView.resumeRendering();//恢复3D渲染和跟踪
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        panoWidgetView.shutdown();//关闭渲染下并释放相关的内存
        if (backgroundImageLoaderTask != null)
            backgroundImageLoaderTask.cancel(true);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        systemUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        systemUtil.onActivityResult(this, requestCode, resultCode, data, new OnCallback() {

            @Override
            public void call(ImageEntity entity) {
                backgroundImageLoaderTask = new ImageLoaderTask();
                backgroundImageLoaderTask.execute(Pair.create(entity.bitmap, panoOptions));
            }
        });
    }
}
